<template>
    <div class="bg-white p-4 rounded-lg shadow">
        <!-- 搜索区域 -->
        <div class="mb-4 flex items-center space-x-4">
            <el-input v-model="searchParams.keyword" placeholder="请输入角色名称" class="!w-60" clearable />
            <el-button type="primary" @click="handleSearch">
                <el-icon>
                    <Search />
                </el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
                <el-icon>
                    <Refresh />
                </el-icon>重置
            </el-button>
        </div>

        <!-- 操作按钮区域 -->
        <div class="mb-4">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增角色
            </el-button>
        </div>

        <!-- 表格区域 -->
        <el-table :data="tableData" border stripe v-loading="loading">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleKey" label="角色标识" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                        {{ row.status === '1' ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="primary" @click="handlePermission(row)">权限设置</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="mt-4 flex justify-end">
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size" :total="page.total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 角色表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '新增角色' : '编辑角色'" width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色标识" prop="roleKey">
                    <el-input v-model="form.roleKey" placeholder="请输入角色标识" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="0" :max="999" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="'1'" :inactive-value="'0'" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>

        <!-- 权限设置对话框 -->
        <el-dialog v-model="permissionVisible" title="权限设置" width="400px">
            <el-tree ref="treeRef" :data="menuTree" show-checkbox node-key="id" :props="{ label: 'title' }" />
            <template #footer>
                <el-button @click="permissionVisible = false">取消</el-button>
                <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'

// 搜索参数
const searchParams = reactive({
    keyword: ''
})

// 分页参数
const page = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 表单相关
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = reactive({
    id: '',
    roleName: '',
    roleKey: '',
    sort: 0,
    status: '1',
    remark: ''
})

// 表单校验规则
const rules = reactive<FormRules>({
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' }
    ],
    roleKey: [
        { required: true, message: '请输入角色标识', trigger: 'blur' }
    ]
})

// 权限树相关
const permissionVisible = ref(false)
const treeRef = ref()
const menuTree = ref([])
const currentRoleId = ref('')

// 获取表格数据
const getTableData = async () => {
    loading.value = true
    try {
        // TODO: 调用API获取数据
        // const res = await getRoleList({ ...searchParams, ...page })
        // tableData.value = res.data.list
        // page.total = res.data.total
    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}

// 获取菜单树数据
const getMenuTree = async () => {
    try {
        // TODO: 调用API获取菜单树数据
        // const res = await getMenuTree()
        // menuTree.value = res.data
    } catch (error) {
        console.error(error)
    }
}

// 搜索
const handleSearch = () => {
    page.current = 1
    getTableData()
}

// 重置搜索
const resetSearch = () => {
    searchParams.keyword = ''
    handleSearch()
}

// 新增
const handleAdd = () => {
    formType.value = 'add'
    form.id = ''
    form.roleName = ''
    form.roleKey = ''
    form.sort = 0
    form.status = '1'
    form.remark = ''
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    formType.value = 'edit'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该角色吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            // TODO: 调用删除API
            // await deleteRole(row.id)
            ElMessage.success('删除成功')
            getTableData()
        } catch (error) {
            console.error(error)
        }
    })
}

// 权限设置
const handlePermission = async (row: any) => {
    currentRoleId.value = row.id
    await getMenuTree()
    // TODO: 获取角色已有权限
    // const res = await getRolePermissions(row.id)
    // treeRef.value.setCheckedKeys(res.data)
    permissionVisible.value = true
}

// 提交权限设置
const handlePermissionSubmit = async () => {
    const checkedKeys = treeRef.value.getCheckedKeys()
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
    try {
        // TODO: 调用保存权限API
        // await saveRolePermissions({
        //     roleId: currentRoleId.value,
        //     menuIds: [...checkedKeys, ...halfCheckedKeys]
        // })
        ElMessage.success('保存成功')
        permissionVisible.value = false
    } catch (error) {
        console.error(error)
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // TODO: 调用保存API
                // if (formType.value === 'add') {
                //     await addRole(form)
                // } else {
                //     await updateRole(form)
                // }
                ElMessage.success(formType.value === 'add' ? '新增成功' : '更新成功')
                dialogVisible.value = false
                getTableData()
            } catch (error) {
                console.error(error)
            }
        }
    })
}

// 分页相关
const handleSizeChange = (val: number) => {
    page.size = val
    getTableData()
}

const handleCurrentChange = (val: number) => {
    page.current = val
    getTableData()
}

// 初始化
getTableData()
</script>
